from urllib.parse import urljoin

import aiohttp

from app.bot.utils.logger import log


async def make_request(
    url: str, headers: dict, method: str = "get", post_data: dict = None
) -> dict:
    async with aiohttp.ClientSession(headers=headers) as session:
        if method == "post" and post_data:
            async with session.post(
                url, json=post_data, verify_ssl=False, allow_redirects=False
            ) as req_:
                return await req_.json()
        else:
            async with session.get(
                url, verify_ssl=False, allow_redirects=False
            ) as req_:
                return await req_.json()


async def check_token(panel_ip: str, token: str) -> bool:
    headers = {
        "Authorization": token,
        "Content-Type": "application/json",
    }
    url = urljoin(panel_ip, "/new/accounts/")
    try:
        resp = await make_request(url, headers)
        if not resp.get("success") and "auth error" in resp.get("errors"):
            return False
        else:
            return True
    except Exception as e:
        log.exception(e)
        return False


async def add_account(panel_ip: str, token: str, account: list) -> dict | bool:
    try:
        headers = {
            "Authorization": token,
            "Content-Type": "application/json",
        }
        url = urljoin(panel_ip, "/new/accounts/add")
        post_data = {
            "name": account[0],
            "access_token": account[4],
            "useragent": account[3],
            "cookies": account[2],
            "password": account[1],
        }
        resp = await make_request(url, headers, method="post", post_data=post_data)
        return resp
    except Exception as e:
        log.exception(e)
        return False
